package com.woniuxy.system.controller;

import com.woniuxy.system.common.Result;
import com.woniuxy.system.common.enums.impl.BusinessCode;
import com.woniuxy.system.common.exception.Asserts;
import com.woniuxy.system.entity.Manager;
import com.woniuxy.system.model.dto.ManagerDto;
import com.woniuxy.system.model.vo.TokenVo;
import com.woniuxy.system.service.IManagerService;
import com.woniuxy.system.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 内部员工信息 前端控制器
*/
@RestController
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private IManagerService managerService;
    @Value("${jwt.accessTime}")
    private Long accessTime;
    @Value("${jwt.refreshTime}")
    private Long refreshTime;
    @Value("${jwt.signature}")
    private String signature;

    /**
     * 登录返回双token：长短token
     */
    @PostMapping("/login")
    public Result<TokenVo> login(@RequestBody ManagerDto managerDto, HttpServletRequest request){
        // 根据账号密码查询数据库
        Manager manager =
                managerService.login(managerDto.getUserName(),managerDto.getUserPassword());
        Asserts.error(Objects.isNull(manager), BusinessCode.LOGIN_FAILED);

        // 生成短token，用来访问资源
        String accessToken = TokenUtils.createToken(manager.getId(),signature,accessTime,TimeUnit.MINUTES,request);
        // 生成长token，用来置换短token
        String refreshToken = TokenUtils.createToken(manager.getId(),signature,refreshTime,TimeUnit.DAYS,request);

        // 返回对象
        TokenVo tokenVo = new TokenVo(
                manager.getId(),manager.getUserName(),accessToken,refreshToken);
        return Result.ok(tokenVo);
    }
}












